import { ref } from 'vue';
import { Type } from 'protobufjs';
import { Messages, DecodeMessage, useLoadProtoGetType, useDecodeBufferHook } from './proto';
import { useParseLiveHook } from './parse-live-hook';

const protoSrc = 'proto/msg.proto';
// 解析直播地址
export const useAnalysisLiveHook = async ({ typeName = 'msg.MsgData', url = '' }: { typeName?: string; url?: string }) => {
  const { parseLiveBuffer } = await useParseLiveHook('list.ParseLive', url);
  const msgData = await useMsgDataHook({ typeName, type: 1001, buffer: parseLiveBuffer.value as Uint8Array });
  return {
    ...msgData
  };
};

export const useMsgDataHook = async ({
  typeName,
  type,
  buffer
}: {
  typeName: string;
  type: number;
  buffer: Uint8Array;
}) => {
  const msgType = ref<Type>();
  const msgMessage = ref<Messages>();
  const msgBuffer = ref<Uint8Array>();
  msgType.value = await useLoadProtoGetType({ typeName, protoSrc });
  msgMessage.value = msgType.value?.create({
    type,
    data: buffer
  }) as Messages;
  msgBuffer.value = msgType.value?.encode(msgMessage.value).finish();
  return {
    msgType,
    msgMessage,
    msgBuffer
  };
};

export const useDecodeMsgHook = async ({ uint8Array }: DecodeMessage) => {
  if (!uint8Array) return '';
  const typeName = 'msg.MsgData';
  const decodeData = await useDecodeBufferHook({ protoSrc, typeName, uint8Array });
  return decodeData;
};
